package com.example.boss.pinkdiary;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Looper;
import android.support.design.widget.FloatingActionButton;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ArrayAdapter;
import android.text.TextUtils;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.boss.db.gen.DaoMaster;
import com.example.boss.db.gen.DaoSession;
import com.example.boss.db.gen.diaryList;
import com.example.boss.db.gen.diaryListDao;
import com.example.boss.db.gen.diaryPwd;
import com.example.boss.db.gen.diaryPwdDao;
import com.example.boss.db.gen.diaryTag;
import com.example.boss.db.gen.diaryTagDao;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static android.R.attr.data;

//implements SearchView.OnQueryTextListener
public class PinkMain extends AppCompatActivity {
    private View v;
    private FloatingActionButton write_fab, up_fab;
    private pinkScrollView sv;
    private ActionBar actionBar;
    private ImageButton bt;
    // GreenDAO使用的变量
    private SQLiteDatabase db3;
    private DaoMaster daoMaster3;
    private DaoSession daoSession3;
    private diaryPwdDao dpd;
    private diaryPwd dp;
    private diaryPwdDaoHelper dpdh;
    // GreenDAO使用的变量
    private SQLiteDatabase db1, db2;
    private DaoMaster daoMaster1, daoMaster2;
    private DaoSession daoSession1, daoSession2;
    private diaryListDao dld;
    private diaryList dl;
    private diaryTagDao dtd;
    private diaryTag dt;
    private diaryListDaoHelper dldh;
    private List<diaryList> diary_List;
    private List<diaryList> diary_List_orderByDate_ASC;
    private List<diaryList> diary_List_orderByDate_Desc;
    private List<diaryList> diary_List_selectByPrivate;
    private RecyclerView recyclerView, recyclerView2;
    private diaryListAdapter dAdapter;

    private PopupMenu popupMenu;
    private int desc = 1, asc = 0;//区分点击显示或隐藏私密日记时，当前日记的排序
    private int d_private = 0, d_no_private = 1;//区分点击升序或降序时，当前日记是否显示私密
    private ImageView lock_iv;
    private Intent intent1;
    private Intent intent2;

    private int check_menu = 0;//检测多选菜单是否出现
    private LinearLayout lay;
    private List<String> checkBox = new ArrayList<String>();
    ;
    private int listNum = 0;
    private List<CheckBox> cb = new ArrayList<CheckBox>();
    private List<CheckBox> cb2 = new ArrayList<CheckBox>();
    private List<String> get_listDate = new ArrayList<String>();
    private ImageView operate_delete, operate_back;
    private AlertDialog.Builder builder;
    private int longCheck = 0;//当前是否在长按删除中

    private ImageButton write_ab_search, write_ab_bj;
    private ImageView search_back, search_time, search_press_time;
    private RelativeLayout search;
    private int search_if = 0;//判断是否正在显示搜索框
    private EditText search_editText;
    private String key = "", timekey = "";//搜索框输入的文本
    private int searchTime = 0;//判断是否正在搜索时间

    private TextView addTag, checkTag, default_tv;
    private writeDialogAdapter wAdapter;
    private PopupWindow popupWindow;
    AlertDialog.Builder builder2;
    private EditText tag_et;
    private String get_editview_tag;
    private diaryTagDaoHelper dtdh;
    private TextView pre_selectTag,cur_selectTag;//之前选择的标签，当前标签
    private int result;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;
    private String emailTo;//收件人邮箱地址
    private String mailFrom;//发件人邮箱地址
    private String mailPwd;//发件人授权码
    private ImageView plane;
    private String code,edit_code;
    private EditText send_code,input_alterPsw;
    private String inputAlterPsw="";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.colorPrimary_two);//通知栏所需颜色
        }
        setContentView(R.layout.pink_main);
        intent1 = getIntent();// 获取意图对象
        if (intent1.getExtras() != null) {
            desc = Integer.parseInt(intent1.getStringExtra("data1"));
            d_private = Integer.parseInt(intent1.getStringExtra("data2"));
        }
        InitDAO_tag();
        InitDAO_list();
        InitDAO_pwd();
        initView();
        actionbarInit();

        // getSearch();
        writeListener();
        scrollViewListener();
        upListener();
        imageButtonListener();
        initDialog();
        searchListener();
        searchBackListener();
        searchEditTextListener();
        searchTimeListener();
        searchPressTimeListener();
        tagListener();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }
    private void InitDAO_tag() {
        DaoMaster.DevOpenHelper helper1 = new DaoMaster.DevOpenHelper(this, "diary_Tag.db", null);
        db1 = helper1.getWritableDatabase();
        daoMaster1 = new DaoMaster(db1);//代表着一个数据库的连接
        daoSession1 = daoMaster1.newSession();//可以让我们使用一些Entity的基本操作和获取Dao操作类
        dtd = daoSession1.getDiaryTagDao();
        dtdh = new diaryTagDaoHelper(dtd);
//        diaryTag dx=new diaryTag();
//        dx.setTag("全部");
//        dtd.insert(dx);
//       dtd.deleteAll();
    }

    private void InitDAO_list() {
        DaoMaster.DevOpenHelper helper2 = new DaoMaster.DevOpenHelper(this, "diary_List.db", null);
        db2 = helper2.getWritableDatabase();
        daoMaster2 = new DaoMaster(db2);//代表着一个数据库的连接
        daoSession2 = daoMaster2.newSession();//可以让我们使用一些Entity的基本操作和获取Dao操作类
        dld = daoSession2.getDiaryListDao();
//dld.deleteAll();
    }

    private void InitDAO_pwd() {
        DaoMaster.DevOpenHelper helper3 = new DaoMaster.DevOpenHelper(this, "diary_Pwd.db", null);
        db3 = helper3.getWritableDatabase();
        daoMaster3 = new DaoMaster(db3);//代表着一个数据库的连接
        daoSession3 = daoMaster3.newSession();//可以让我们使用一些Entity的基本操作和获取Dao操作类
        dpd = daoSession3.getDiaryPwdDao();
        dpdh=new diaryPwdDaoHelper(dpd);
    }

    public void showList(final List<diaryList> list, String key) {
        longCheck = 0;
        recyclerView = (RecyclerView) findViewById(R.id.main_rcv);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));//设置线性管理器
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        dAdapter = new diaryListAdapter(this, list, key);
        recyclerView.setAdapter(dAdapter);
        listNum = list.size();
        dAdapter.setOnItemClickListener(new diaryListAdapter.ItemClickListener() {
            @Override
            public void checkBoxClick(int position) {

            }

            @Override
            public void onItemClick(View view, int position, String lock) {
                View ItemView = recyclerView.getChildAt(position);
                System.out.print(ItemView);
                TextView get_day = (TextView) ItemView.findViewById(R.id.tv_day);
                TextView get_month = (TextView) ItemView.findViewById(R.id.tv_month);
                TextView get_year = (TextView) ItemView.findViewById(R.id.tv_year);
                TextView get_time = (TextView) ItemView.findViewById(R.id.tv_time);
                TextView get_title = (TextView) ItemView.findViewById(R.id.tv_title);
                TextView get_content = (TextView) ItemView.findViewById(R.id.tv_content);

                String s[] = get_month.getText().toString().split("\\/");
                String cut_month = s[0];
                String get_date = get_year.getText().toString() + "/" + cut_month + get_day.getText().toString() + "日/" + get_time.getText().toString();
                String update = "1";
                String title = get_title.getText().toString();
                String content = get_content.getText().toString();
                intent2 = new Intent(PinkMain.this, PinkWrite.class);// 添加点击响应事件
                intent2.putExtra("data1", get_date); //设置传递键值对
                intent2.putExtra("data2", update);
                intent2.putExtra("data3", desc + "");
                intent2.putExtra("data4", d_private + "");
                intent2.putExtra("data5", title);
                intent2.putExtra("data6", content);
                intent2.putExtra("data7", lock);
                startActivity(intent2);//启动
                finish();
            }

            @Override
            public boolean onItemLongClick(View view, int position) {
                View ItemView = recyclerView.getChildAt(position);
                for (int i = 0; i < listNum; i++) {
                    cb.add((CheckBox) recyclerView.getChildAt(i).findViewById(R.id.listview_select_cb));
                }
                for (int i = 0; i < listNum; i++) {
                    cb.get(i).setVisibility(View.VISIBLE);
                }
                lay = (LinearLayout) findViewById(R.id.lay);
                lay.startAnimation(getAnimation());
                lay.setVisibility(View.VISIBLE);
                check_menu = 1;
                write_fab.setVisibility(View.INVISIBLE);
                up_fab.setVisibility(View.INVISIBLE);
                longCheck = 1;
                deleteListener();
                returnListener();
                return true;
            }
        });
    }

    protected Animation getAnimation() {//设置layout动画
        Animation anim = new ScaleAnimation(1.0f, 1.0f, 0.0f, 1.0f,
                Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF,
                1.0f);// 从0.5倍放大到1倍
        anim.setDuration(200);
        return anim;
    }

    public void returnListener() {//监听底端菜单返回按钮
        operate_back = (ImageView) findViewById(R.id.operate_back);
        operate_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                for (int i = 0; i < cb.size(); i++) {
                    cb.get(i).setChecked(false);
                }
                lay.setVisibility(View.INVISIBLE);
                check_menu = 0;
                write_fab.setVisibility(View.VISIBLE);
                up_fab.setVisibility(View.VISIBLE);
                for (int i = 0; i < listNum; i++) {
                    cb.get(i).setVisibility(View.GONE);
                }
                cb.clear();
                get_listDate.clear();
            }
        });
    }

    public void deleteListener() {//监听删除titem按钮
        operate_delete = (ImageView) findViewById(R.id.operate_delete);
        operate_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int isChecked_num = 0;
                cb2.clear();
                for (int i = 0; i < listNum; i++) {
                    if (cb.get(i).isChecked()) {
                        isChecked_num++;
                        cb2.add((CheckBox) recyclerView.getChildAt(i).findViewById(R.id.listview_select_cb));
                        TextView year = (TextView) recyclerView.getChildAt(i).findViewById(R.id.tv_year);
                        TextView month = (TextView) recyclerView.getChildAt(i).findViewById(R.id.tv_month);
                        TextView day = (TextView) recyclerView.getChildAt(i).findViewById(R.id.tv_day);
                        TextView time = (TextView) recyclerView.getChildAt(i).findViewById(R.id.tv_time);
                        String g_year = year.getText().toString();
                        String str[] = month.getText().toString().split("\\/");
                        String g_month = str[0];
                        String g_day = day.getText().toString();
                        String g_time = time.getText().toString();
                        get_listDate.add(g_year + "/" + g_month + g_day + "日/" + g_time);
                    }
                }
                if (isChecked_num > 0) {
                    isChecked_num = 0;
                    builder.show();
                } else Toast.makeText(PinkMain.this, "未选中日记", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initDialog() {//退出时弹出对话框确认是否退出
        builder = new AlertDialog.Builder(this).setIcon(R.drawable.heart)
                .setTitle("确定删除日记？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        for (int i = 0; i < get_listDate.size(); i++) {
                            dldh.deleteByDate(get_listDate.get(i));
                        }
                        lay.setVisibility(View.INVISIBLE);
                        check_menu = 0;
                        write_fab.setVisibility(View.VISIBLE);
                        up_fab.setVisibility(View.VISIBLE);
                        for (int i = 0; i < listNum; i++) {
                            cb.get(i).setVisibility(View.GONE);
                        }
                        cb.clear();
                        get_listDate.clear();
                        List<diaryList> new_list;
                        if (desc == 1) new_list = dldh.orderByDate_Desc(d_private);
                        else new_list = dldh.orderByDate_Asc(d_private);
                        showList(new_list, key);
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        get_listDate.clear();
                    }
                });
    }

    public void initView() {
        actionBar = getSupportActionBar();
        sv = (pinkScrollView) findViewById(R.id.PinkMain_sv);
        write_fab = (FloatingActionButton) findViewById(R.id.write_fab);
        up_fab = (FloatingActionButton) findViewById(R.id.up_fab);
        mailFrom = "13192268860@163.com";
        mailPwd = "1234qwer";
        List<diaryPwd> selectList;
        selectList=dpd.loadAll();
        emailTo=selectList.get(0).getEmail();
        dldh = new diaryListDaoHelper(dld);
        if (desc == 1) diary_List = dldh.orderByDate_Desc(d_private);
        else diary_List = dldh.orderByDate_Asc(d_private);
        popupMenu = new PopupMenu(this, bt);
        popupMenu.getMenuInflater().inflate(R.menu.main_actionbar_menu, popupMenu.getMenu());
        showList(diary_List, key);
    }

    public void planeListener() {
        plane.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                char[] c = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
                StringWidthWeightRandom random = new StringWidthWeightRandom(c);
                code = random.getNextString(6);
                final String content = "PinkDiary发送来验证码:" + code + ",如非本人操作请忽略。";
                if(emailTo.equals("")){
                    Toast.makeText(PinkMain.this, "邮箱不得为空", Toast.LENGTH_LONG).show();
                }
                else{
                    Thread thread = new Thread() {
                        @Override
                        public void run() {
                            EmailUtil.getInstance().sendEmail(mailFrom, mailPwd, emailTo, "发送验证码", content);//耗时操作，必须在线程中进行
                            //线程中弹出Toast
                            Looper.prepare();
                            Toast.makeText(PinkMain.this, "验证码已发送", Toast.LENGTH_LONG).show();
                            Looper.loop();
                        }
                    };
                    thread.start();
                }

            }
        });
    }
    public void pswListener(){//监听密码框
        input_alterPsw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                inputAlterPsw=input_alterPsw.getText().toString();
            }
        });
    }
    public void sendCodeListener() {//监听验证码输入框
        send_code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                edit_code=send_code.getText().toString();
            }
        });
    }

    public void actionbarInit() {//自定义actionbar
        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setDisplayShowTitleEnabled(true);
        if (actionBar != null) {
            actionBar.setCustomView(R.layout.main_actionbar_custom);//设置自定义的布局
        }
        bt = (ImageButton) findViewById(R.id.write_ab_more);
        write_ab_search = (ImageButton) findViewById(R.id.write_ab_search);
        write_ab_bj = (ImageButton) findViewById(R.id.write_ab_bj);
        search = (RelativeLayout) findViewById(R.id.search);
        search_back = (ImageView) findViewById(R.id.search_back);
        search_time = (ImageView) findViewById(R.id.search_time);
        search_press_time = (ImageView) findViewById(R.id.search_press_time);
        search_editText = (EditText) findViewById(R.id.search_editText);
    }

    public void imageButtonListener() {//更多按钮的点击监听
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupMenu(bt);
            }
        });
    }

    private void showPopupMenu(View view) {//点击按钮出现悬浮菜单
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.alter_pwd:{
                        alterPwdListener();
                        break;
                    }

                    case R.id.diary_no_private: {
                        diary_List_selectByPrivate = dldh.select_no_private(desc);
                        showList(diary_List_selectByPrivate, key);
//                        now_list=diary_List_selectByPrivate;
                        popupMenu.getMenu().findItem(R.id.diary_private).setVisible(true);
                        popupMenu.getMenu().findItem(R.id.diary_no_private).setVisible(false);
                        d_private = 0;
                        d_no_private = 1;
                        break;
                    }
                    case R.id.diary_private: {
                        inputPwd();

                        break;
                    }
                    case R.id.diary_orderByDate_Asc: {
                        diary_List_orderByDate_ASC = dldh.orderByDate_Asc(d_private);
                        showList(diary_List_orderByDate_ASC, key);
//                        now_list=diary_List_orderByDate_ASC;
                        popupMenu.getMenu().findItem(R.id.diary_orderByDate_Asc).setVisible(false);
                        popupMenu.getMenu().findItem(R.id.diary_orderByDate_Desc).setVisible(true);
                        desc = 0;
                        asc = 1;
                        break;
                    }
                    case R.id.diary_orderByDate_Desc: {
                        diary_List_orderByDate_Desc = dldh.orderByDate_Desc(d_private);
                        showList(diary_List_orderByDate_Desc, key);
//                        now_list=diary_List_orderByDate_Desc;
                        popupMenu.getMenu().findItem(R.id.diary_orderByDate_Asc).setVisible(true);
                        popupMenu.getMenu().findItem(R.id.diary_orderByDate_Desc).setVisible(false);
                        desc = 1;
                        asc = 0;
                        break;
                    }
                }
                return true;
            }
        });
        if (d_private == 0) popupMenu.getMenu().findItem(R.id.diary_private).setVisible(true);
        else popupMenu.getMenu().findItem(R.id.diary_no_private).setVisible(true);
        if (desc == 1) popupMenu.getMenu().findItem(R.id.diary_orderByDate_Asc).setVisible(true);
        else popupMenu.getMenu().findItem(R.id.diary_orderByDate_Desc).setVisible(true);
        popupMenu.show();
    }
    public void alterPwdListener(){//点击重置密码修改密码
        LayoutInflater factory = LayoutInflater.from(PinkMain.this);//提示框
        final View view = factory.inflate(R.layout.alter_psw, null);
        plane=(ImageView) view.findViewById(R.id.send);
        send_code=(EditText) view.findViewById(R.id.send_code);
        input_alterPsw=(EditText) view.findViewById(R.id.inputPsw_et);

        planeListener();
        sendCodeListener();
        pswListener();
        new AlertDialog.Builder(this).setTitle("请输入新密码").setIcon(R.drawable.heart)
                .setView(view)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if(!edit_code.equals(code)){
                            Toast.makeText(PinkMain.this, "验证码输入错误", Toast.LENGTH_LONG).show();
                            send_code.setText("");
                        }
                        else{
                            if(inputAlterPsw.equals("")){
                                Toast.makeText(PinkMain.this, "密码不得为空", Toast.LENGTH_LONG).show();
                            }
                            else{
                                diaryPwd updateList=  dpd.queryBuilder().where(diaryPwdDao.Properties.Email.eq(emailTo)).build().unique();
                                updateList.setPwd(inputAlterPsw);
                                dpd.update(updateList);
                            }
                        }

                    }
                }).setNegativeButton("取消",null).show();

    }
    public void inputPwd(){//点击查看私密日记之后弹出输入密码框
        LayoutInflater factory = LayoutInflater.from(PinkMain.this);//提示框
        final View view = factory.inflate(R.layout.input_psw, null);
        new AlertDialog.Builder(this).setTitle("请输入密码").setIcon(R.drawable.heart)
                .setView(view)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        EditText input_psw=(EditText) view.findViewById(R.id.inputPsw_et);
                        final String inputPsw=input_psw.getText().toString();
                        result=dpdh.selectPwd(inputPsw);

                        if(result==0){
                            Toast.makeText(PinkMain.this, "密码错误", Toast.LENGTH_SHORT).show();
                        }
                        else{
                            diary_List_selectByPrivate = dldh.select_private(desc);
                            d_private = 1;
                            d_no_private = 0;
                            showList(diary_List_selectByPrivate, key);
                            popupMenu.getMenu().findItem(R.id.diary_private).setVisible(false);
                            popupMenu.getMenu().findItem(R.id.diary_no_private).setVisible(true);
                        }
                    }
                }).setNegativeButton("取消",null).show();
    }
    public void scrollViewListener() {//滚动条的滑动监听
        sv.setOnScrollListener(new pinkScrollView.OnScrollListener() {
            @Override
            public void onScroll(int scrolly) {
                if (longCheck == 0) {
                    if (scrolly > 100) {
                        up_fab.setVisibility(View.VISIBLE);
                        write_fab.setVisibility(View.INVISIBLE);
                    } else {
                        write_fab.setVisibility(View.VISIBLE);
                        up_fab.setVisibility(View.INVISIBLE);
                    }
                }
            }
        });
        upListener();
    }

    public void upListener() {//up悬浮按钮的点击事件的监听
        up_fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sv.scrollTo(0, 0);//ScrollView返回到顶部
            }
        });
    }

    public void writeListener() {//编辑悬浮按钮的点击事件的监听
        write_fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(PinkMain.this, PinkWrite.class);// 添加点击响应事件
                startActivity(intent);//启动
            }
        });
    }

    public void searchListener() {//搜索按钮监听
        write_ab_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                search_if = 1;
                write_ab_search.setVisibility(View.GONE);
                write_ab_bj.setVisibility(View.GONE);
                bt.setVisibility(View.GONE);
                search.setVisibility(View.VISIBLE);
            }
        });
    }

    public void searchEditTextListener() {//搜索editText监听
        search_editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (searchTime == 0) {
                    key = search_editText.getText().toString();
                    diary_List = dldh.selectByKey(key, desc, d_private);
                    showList(diary_List, key);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (searchTime == 0) {
                    key = search_editText.getText().toString();
                    diary_List = dldh.selectByKey(key, desc, d_private);
                    showList(diary_List, key);
                } else {
                    timekey = search_editText.getText().toString();
                    diary_List = dldh.selectByTimeKey(timekey, desc, d_private);
                    showList(diary_List, key);
                }
            }
        });
    }

    public void searchBackListener() {//搜索框返回键监听
        search_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                write_ab_search.setVisibility(View.VISIBLE);
                write_ab_bj.setVisibility(View.VISIBLE);
                bt.setVisibility(View.VISIBLE);
                search.setVisibility(View.GONE);
                search_if = 0;
                diary_List = dldh.select(desc, d_private);
                key = "";
                search_editText.setText("");
                showList(diary_List, key);
                search_time.setVisibility(View.VISIBLE);
                search_press_time.setVisibility(View.GONE);
                search_editText.setHint("搜索关键字");
            }
        });
    }

    public void searchTimeListener() {//监听搜索框的日历键
        search_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                search_time.setVisibility(View.GONE);
                search_press_time.setVisibility(View.VISIBLE);
                searchTime = 1;
                search_editText.setHint("格式:2018(/6月)(16日)(之前)");
            }
        });
    }

    public void searchPressTimeListener() {//监听搜索框的日历键
        search_press_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                search_time.setVisibility(View.VISIBLE);
                search_press_time.setVisibility(View.GONE);
                searchTime = 0;
                search_editText.setText("");
                search_editText.setHint("搜索关键字");
            }
        });
    }

    public void tagListener() {//监听标签键
        write_ab_bj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupWindow();
            }
        });
    }
    private int changeTagNum=0,pre_position=0;
    private void showPopupWindow() {//设置底部弹出框
        List<diaryTag> tagList = dtd.loadAll();
        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View parent_view = LayoutInflater.from(PinkMain.this).inflate(R.layout.pink_main, null);
        View view = layoutInflater.inflate(R.layout.write_dialog, null);
        default_tv = (TextView) view.findViewById(R.id.default_tv);
        if(pre_selectTag==null){
            pre_selectTag=default_tv;
        }
        addTag = (TextView) view.findViewById(R.id.write_dialog_tv);
        defaultListener();
        addTagListener();
        recyclerView2 = (RecyclerView) view.findViewById(R.id.select);
        recyclerView2.setLayoutManager(new LinearLayoutManager(this));//设置线性管理器
        wAdapter = new writeDialogAdapter(tagList);
        recyclerView2.setAdapter(wAdapter);
        popupWindow = new PopupWindow(view, 1000, 500);
        popupWindow.setContentView(view);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        popupWindow.setAnimationStyle(R.style.BottomDialogAnimation);
        popupWindow.showAtLocation(findViewById(R.id.pink_main), Gravity.BOTTOM, 0, 0);
//        if(pre_selectTag==null){
//            pre_selectTag=default_tv;
//        }
//        else{
//            pre_selectTag.setBackgroundResource(R.color.colorPressbg);
//            pre_selectTag.setTextColor(Color.WHITE);
//        }
        wAdapter.setOnItemClickListener(new writeDialogAdapter.ItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                pre_selectTag.setBackgroundResource(R.color.transparent);
                pre_selectTag.setTextColor(getResources().getColor(R.color.colorPressPop));
                checkTag = (TextView) recyclerView2.getChildAt(position).findViewById(R.id.item_tv);
                checkTag.setBackgroundResource(R.color.colorPressbg);
                checkTag.setTextColor(Color.WHITE);
                pre_selectTag=(TextView) recyclerView2.getChildAt(position).findViewById(R.id.item_tv);
//                cur_selectTag=checkTag;
                String selectTag = checkTag.getText().toString();
                List<diaryList> selectTagList;
                selectTagList = dldh.selectByTag(selectTag, desc, d_private);
                showList(selectTagList, key);
            }

            @Override
            public boolean onItemLongClick(View view, int position) {
                checkTag = (TextView) recyclerView2.getChildAt(position).findViewById(R.id.item_tv);
                deleteDialog();
                builder2.show();
                return true;
            }
        });
    }

    public void defaultListener() {//监听全部标签按钮
        default_tv.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                List<diaryList> selectTagList;
                selectTagList = dldh.select(desc, d_private);
                pre_selectTag.setBackgroundResource(R.color.transparent);
                pre_selectTag.setTextColor(getResources().getColor(R.color.colorPressPop));
                default_tv.setBackgroundResource(R.color.colorPressbg);
                default_tv.setTextColor(Color.WHITE);
                pre_selectTag=default_tv;
                showList(selectTagList, key);
            }
        });
    }

    public void addTagListener() {//监听弹出框中编辑标签按钮
        addTag.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                textAlertDialog();
            }
        });
    }

    public void textAlertDialog() {//弹出框填写需要添加的Tag
        LayoutInflater factory = LayoutInflater.from(PinkMain.this);//提示框
        final View view = factory.inflate(R.layout.add_tag, null);

        new AlertDialog.Builder(PinkMain.this).setIcon(R.drawable.heart)
                .setTitle("添加你喜欢的标签吧")//提示框标题
                .setView(view)
                .setPositiveButton("确定",//提示框的两个按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                tag_et = (EditText) view.findViewById(R.id.tag_et);
                                get_editview_tag = tag_et.getText().toString();
                                insertTag();
                                dialog.dismiss();
                                popupWindow.dismiss();
                                showPopupWindow();
                            }
                        }).setNegativeButton("取消", null).create().show();
    }

    public void insertTag() {//判断添加的tag是否已经存在
        int num = dtdh.judgeByTag(get_editview_tag);
        if (num == 0) {
            diaryTag saveTag = new diaryTag();
            saveTag.setTag(get_editview_tag);
            dtd.insert(saveTag);
        } else {
            Toast.makeText(PinkMain.this, "添加的标签已存在", Toast.LENGTH_SHORT).show();
        }
    }

    private void deleteDialog() {//退出时弹出对话框确认是否退出
        builder2 = new AlertDialog.Builder(this,R.style.MyAlertDialogStyle).setIcon(R.drawable.heart)
                .setTitle("确定删除标签？")
                .setMessage("删除之后该标签下的日记将转存入“全部”标签")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        transferTag(checkTag);
                        deleteTag(checkTag);
                        popupWindow.dismiss();
                        showPopupWindow();
                        dialog.dismiss();
                        List<diaryList> transferList=dldh.select(desc,d_private);
                        showList(transferList,key);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
    }

    public void deleteTag(TextView checkTag) {
        String tag = checkTag.getText().toString();
        dtdh.deleteByTag(tag);
    }
    public void transferTag(TextView checkTag){
        String transferTag=checkTag.getText().toString();
        diaryList updateList = dld.queryBuilder().where(diaryListDao.Properties.Tag.eq(transferTag)).build().unique();
        updateList.setTag("全部");
        dld.update(updateList);
    }
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        initView();
    }

    @Override
    public void onBackPressed() {//按下底部返回键时
        if (search_if == 1) {
            write_ab_search.setVisibility(View.VISIBLE);
            write_ab_bj.setVisibility(View.VISIBLE);
            bt.setVisibility(View.VISIBLE);
            search.setVisibility(View.GONE);
            search_if = 0;
            diary_List = dldh.select(desc, d_private);
            key = "";
            search_editText.setText("");
            showList(diary_List, key);
            search_time.setVisibility(View.VISIBLE);
            search_press_time.setVisibility(View.GONE);
            search_editText.setHint("搜索关键字");
        } else {
            if (check_menu == 0) {
                this.finish();
            } else {
                for (int i = 0; i < cb.size(); i++) {
                    cb.get(i).setChecked(false);
                }
                lay.setVisibility(View.INVISIBLE);
                check_menu = 0;
                write_fab.setVisibility(View.VISIBLE);
                up_fab.setVisibility(View.VISIBLE);
                for (int i = 0; i < listNum; i++) {
                    cb.get(i).setVisibility(View.GONE);
                }
                cb.clear();
                get_listDate.clear();
            }
        }
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("PinkMain Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }
}